package ggze.GGZEServer.home.service.impl;

import com.google.gson.Gson;
import ggze.GGZEServer.home.dao.inter.SoTeamUserDao;
import ggze.GGZEServer.home.entity.DataRoleGroup;
import ggze.GGZEServer.home.entity.LookRoleGroup;
import ggze.GGZEServer.home.entity.NavigRoleGroup;
import ggze.GGZEServer.home.entity.SoTeamUser;
import ggze.GGZEServer.home.enums.UserEnum;
import ggze.GGZEServer.home.service.GGZEServerCommonService;
import ggze.actuator.ActuatorController;
import ggze.esp.dao.inter.*;
import ggze.esp.entity.*;
import ggze.tool.BeanToJson;
import ggze.tool.JwtToken;
import ggze.tool.ReturnBody;
import ggze.tool.TimeUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Service
public class GGZEServerCommonsServiceImpl implements GGZEServerCommonService {
    @Autowired
    private MPSDao mpsDao;
    @Autowired
    private FspUserDao userDao;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ActuatorController actuatorController;
    @Autowired
    private FspRoleDao fspRoleDao;
    @Autowired
    private FspUserDao fspUserDao;
    @Autowired
    private FspDataRecordDao fspDataRecordDao;
    @Autowired
    private FspRoleDataDao fspRoleDataDao;
    @Autowired
    private FspRoleLookDao fspRoleLookDao;
    @Autowired
    private FspRoleNavigationDao fspRoleNavigationDao;
    @Autowired
    private SoTeamUserDao soTeamUserDao;
    @Override
    public JSONArray getNav(String userid){
        StringBuilder sql = new StringBuilder();
        sql.append("select * from fsp_navigation where uuid in ( select F_navigation_id from fsp_role_navigation where F_ROLE_CODE = (select F_ROLE_CODE from fsp_user where uuid='"+userid+"') ) and F_STATUS = 0 order by uuid");
        List<Map<String, String>> navList = mpsDao.commonSql(sql.toString());
        List<Map<Object,Object>> rqNav=new LinkedList<Map<Object,Object>>();
        for(Map<String, String> parentNavs:navList){
            String xp=JSONObject.fromObject(parentNavs).toString();
            FspNavigation parentNav = (FspNavigation) BeanToJson.jsonTobean(xp,FspNavigation.class);
            if(StringUtils.isEmpty(parentNav.getF_PARENT_ID())){
                JSONObject par=JSONObject.fromObject(parentNav);
                Map<Object,Object> pars=(Map)par;
                List<Map<Object,Object>> sonNav=new LinkedList<Map<Object,Object>>();
                for(Map<String, String> sons:navList){
                    FspNavigation son = (FspNavigation) BeanToJson.jsonTobean(JSONObject.fromObject(sons).toString(),FspNavigation.class);
                    if(son.getF_PARENT_ID()!=null){
                        if(son.getF_PARENT_ID().equals(parentNav.getUuid())){
                            JSONObject sonJson=JSONObject.fromObject(son);
                            Map<Object,Object> sonMp=(Map)sonJson;
                            sonMp.put("id",sonMp.get("uuid"));
                            sonMp.put("name",sonMp.get("f_NAVIG"));
                            sonMp.put("icon",sonMp.get("f_ICON"));
                            sonMp.put("url","./vsp?code="+sonMp.get("f_URL"));
                            sonNav.add(sonMp);
                        }
                    }
                }
                pars.put("id",par.get("uuid"));
                pars.put("name",par.get("f_NAVIG"));
                pars.put("icon",par.get("f_ICON"));
                pars.put("childList",sonNav);
                rqNav.add(pars);
            }
        }
        return JSONArray.fromObject(rqNav);
    }

    @Override
    public ReturnBody loginSql(JSONObject jsonObject) {
        ReturnBody returnBody=new ReturnBody();
        try {
            String name=jsonObject.getString("name");
            String pass=jsonObject.getString("pass");

            FspUser user= userDao.isSelect("F_IPONE",name);
            if(user==null||"".equals(user)){
                user=userDao.isSelect("F_EMIL",name);
            }
            if(user==null||"".equals(user)){
                returnBody.setCode("1");
                returnBody.setTitle("用户名或密码不正确");
                return returnBody;
            }
            String ps=user.getF_PASSWORD();
            if(!pass.equals(ps)){
                returnBody.setCode("1");
                returnBody.setTitle("密码错误");
                return returnBody;
            }
            if("1".equals(user.getF_STATUS())){
                returnBody.setCode("1");
                returnBody.setTitle("账户已被禁用");
                return returnBody;
            }
            returnBody.setCode("0");
            returnBody.setTitle("成功");
            Map<String, String> bodymap = new LinkedHashMap<String, String>();
            JSONObject token  = new JSONObject();
            token.put("uuid",user.getUuid());
            token.put("time", TimeUtils.getTimeFormat());
            token.put("ip",jsonObject.getString("ip"));
            bodymap.put("token", JwtToken.createToken(token.toString()));
            bodymap.put("user", BeanToJson.toJsonObjectString(user));
            returnBody.setData(BeanToJson.toJsonObjectString(bodymap));
            return returnBody;
        }catch (Exception e){
            e.printStackTrace();
            return returnBody;
        }
    }

    @Override
    public ReturnBody checkIp(JSONObject jsonObject) {
        ReturnBody returnBody=new ReturnBody();
        try {
            String ip=jsonObject.getString("ip");
            String viftoken = JwtToken.verifyToken(jsonObject.getString("token")).get("content").asString();
            JSONObject tokenJSON = JSONObject.fromObject(viftoken);
            if(!ip.equals(tokenJSON.get("ip"))){
                returnBody.setTitle("身份鉴权失败！请重新登录");
                returnBody.setCode("1");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        returnBody.setCode("0");
        return returnBody;
    }
    @Transactional
    @Override
    public ReturnBody regist(JSONObject jsonObject) {
        FspUser entity = (FspUser)BeanToJson.jsonTobean(jsonObject.toString(), FspUser.class);
        ReturnBody returnBody = new ReturnBody();

        try {
           if(StringUtils.isEmpty(entity.getUuid())){
               entity.setUuid("");
               FspUser pe = userDao.isSelect("F_IPONE", entity.getF_IPONE());
               if (pe != null) {
                   returnBody.setCode("1");
                   returnBody.setTitle("手机号已存在");
                   return returnBody;
               }
               FspRole fspRole = fspRoleDao.isSelect("F_ROLE_CODE","ROLE69198995");
               entity.setF_STATUS("0");
               entity.setF_STATUS_NAME(UserEnum.getLables("0"));
               entity.setF_STATE("ROLE69198995");
               entity.setF_STATE_NAME(fspRole.getF_ROLE_NAME());
               String time = TimeUtils.getTimeFormat();
               entity.setF_CREATE_TIME(time);
               entity.setF_METHOD_TIME(time);

               //邀请人
               String inviteID = jsonObject.getString("inviteID");
               if(StringUtils.isEmpty(inviteID)){
                   returnBody.setCode("1");
                   returnBody.setTitle("邀请人为空");
                   return returnBody;
               }
               FspUser inviteUSER = fspUserDao.isSelect("uuid",inviteID);
               if(inviteUSER==null){
                   returnBody.setCode("1");
                   returnBody.setTitle("邀请人不存在");
                   return returnBody;
               }
               String uuid = (String) actuatorController.execute(entity, "add", this.userDao);
               //邀请人的上级树
               SoTeamUser inviteTeam = soTeamUserDao.isSelect("f_user_id",inviteID);
               SoTeamUser soTeamUser  = new SoTeamUser();
               soTeamUser.setF_METHOD_TIME(time);
               soTeamUser.setF_CREATE_TIME(time);
               soTeamUser.setUuid("");
               soTeamUser.setF_INVITE_USER_ID(inviteUSER.getUuid());
               soTeamUser.setF_INVITE_USER_NICKNAME(inviteUSER.getF_NICKNAME());
               soTeamUser.setF_USER_ID(uuid);
               soTeamUser.setF_USER_NICKNAME(entity.getF_NICKNAME());
               soTeamUser.setF_TREE(inviteTeam.getF_TREE()+",''"+inviteID+"''");
               soTeamUser.setF_TREE_NUM(inviteTeam.getF_TREE_NUM()+1);
               actuatorController.execute(soTeamUser,"add",soTeamUserDao);
               returnBody.setCode("0");
               returnBody.setTitle("成功");
           }else{
               FspUser pe = userDao.isSelect("F_IPONE", entity.getF_IPONE());
               if (!entity.getUuid().equals(pe.getUuid())) {
                   returnBody.setCode("1");
                   returnBody.setTitle("手机号已存在");
                   return returnBody;
               }
               FspRole fspRole = fspRoleDao.isSelect("F_ROLE_CODE",entity.getF_STATE());
               entity.setF_STATUS_NAME(UserEnum.getLables(entity.getF_STATUS()));
               entity.setF_STATE_NAME(fspRole.getF_ROLE_NAME());
               String time = TimeUtils.getTimeFormat();
               entity.setF_METHOD_TIME(time);
               actuatorController.execute(entity, "update", this.userDao);
               returnBody.setCode("0");
               returnBody.setTitle("成功");
           }
        } catch (Exception var5) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            returnBody.setCode("1");
            returnBody.setTitle("系统错误");
        }
        return returnBody;
    }

    @Override
    public ReturnBody bind(JSONObject jsonObject) {
        FspUser entity = (FspUser)BeanToJson.jsonTobean(jsonObject.toString(), FspUser.class);
        ReturnBody returnBody = new ReturnBody();
        try {
            entity=fspUserDao.isSelect("uuid",entity.getUuid());
            if(entity.getF_STATUS().equals("1")){
                entity.setF_STATUS("0");
            }
            if(entity.getF_STATUS().equals("0")){
                entity.setF_STATUS("1");
            }
            entity.setF_STATUS_NAME(UserEnum.getLables(entity.getF_STATUS()));
            actuatorController.execute(entity,"update",fspUserDao);
            returnBody.setCode("0");
            returnBody.setTitle("成功");
        } catch (Exception var5) {
            returnBody.setCode("1");
            returnBody.setTitle("系统错误");
        }
        return returnBody;
    }

    @Override
    public ReturnBody roleAdd(JSONObject jsonObject) {
        FspRole entity = (FspRole) BeanToJson.jsonTobean(jsonObject.toString(), FspRole.class);
        ReturnBody returnBody = new ReturnBody();
        try {
            String times = TimeUtils.getTimeFormat();
            if(StringUtils.isEmpty(entity.getUuid())){
                //新增
                entity.setUuid("");
                entity.setF_CREATE_TIME(times);
                entity.setF_METHOD_TIME(times);
                actuatorController.execute(entity,"add",fspRoleDao);
                addRole(entity.getF_ROLE_CODE());
                upRoleNum(entity.getF_ROLE_CODE());
            }else{
                //更新
                entity.setF_METHOD_TIME(times);
                actuatorController.execute(entity,"update",fspRoleDao);
            }
            returnBody.setCode("0");
            returnBody.setTitle("成功");
        } catch (Exception var5) {
            returnBody.setCode("1");
            returnBody.setTitle("系统错误");
        }
        return returnBody;
    }

    @Override
    public ReturnBody roleStateData(JSONObject jsonObject) {
        DataRoleGroup entity = new DataRoleGroup();
        entity.setFspRole((FspRole) BeanToJson.jsonTobean(jsonObject.get("fspRole").toString(), FspRole.class));
        entity.setFspDataRecordList(com.alibaba.fastjson.JSONObject.parseArray(jsonObject.getJSONArray("fspDataRecordList").toString(), FspDataRecord.class));
        ReturnBody returnBody = new ReturnBody();
        try {
            FspRoleData fspRoleDataINS=new FspRoleData();
            fspRoleDataINS.setUuid(" ''");
            StringBuilder del  = new StringBuilder();
            del.append(" ' '");
            for(FspDataRecord fspRoleData:entity.getFspDataRecordList()){
                if(fspRoleDataDao.custom("select * from fsp_role_data where f_role_code = '"+entity.getFspRole().getF_ROLE_CODE()+"' and f_data_id = '"+fspRoleData.getUuid()+"'")==null){
                    fspRoleDataINS.setF_DATA_ID(fspRoleData.getUuid());
                    fspRoleDataINS.setF_ROLE_CODE(entity.getFspRole().getF_ROLE_CODE());
                    actuatorController.execute(fspRoleDataINS,"add",fspRoleDataDao);
                }
                del.append(",'"+fspRoleData.getUuid()+"'");
            }
            mpsDao.commonSqlUp("delete from fsp_role_data where f_data_id not in ("+del.toString()+") and f_role_code = '"+entity.getFspRole().getF_ROLE_CODE()+"'");
            this.upRoleNum(entity.getFspRole().getF_ROLE_CODE());
            returnBody.setCode("0");
            returnBody.setTitle("成功");
        } catch (Exception var5) {
            returnBody.setCode("1");
            returnBody.setTitle("系统错误");
        }
        return returnBody;
    }

    @Override
    public ReturnBody roleStateLook(JSONObject jsonObject) {
        LookRoleGroup entity = new LookRoleGroup();
        entity.setFspRole((FspRole) BeanToJson.jsonTobean(jsonObject.get("fspRole").toString(), FspRole.class));
        entity.setFspLookRecordList(com.alibaba.fastjson.JSONObject.parseArray(jsonObject.getJSONArray("fspLookRecordList").toString(), FspLookRecord.class));
        ReturnBody returnBody = new ReturnBody();
        try {
            FspRoleLook fspRoleLookINS=new FspRoleLook();
            fspRoleLookINS.setUuid("");
            StringBuilder del  = new StringBuilder();
            del.append(" ' '");
            for(FspLookRecord fspLookRecord:entity.getFspLookRecordList()){
                if(fspRoleDataDao.custom("select * from fsp_role_look where f_role_code = '"+entity.getFspRole().getF_ROLE_CODE()+"' and f_look_id = '"+fspLookRecord.getUuid()+"'")==null){
                    fspRoleLookINS.setF_LOOK_ID(fspLookRecord.getUuid());
                    fspRoleLookINS.setF_ROLE_CODE(entity.getFspRole().getF_ROLE_CODE());
                    actuatorController.execute(fspRoleLookINS,"add",fspRoleLookDao);
                }
                del.append(",'"+fspLookRecord.getUuid()+"'");
            }
            mpsDao.commonSqlUp("delete from fsp_role_look where f_look_id not in ("+del.toString()+") and f_role_code = '"+entity.getFspRole().getF_ROLE_CODE()+"'");
            this.upRoleNum(entity.getFspRole().getF_ROLE_CODE());
            returnBody.setCode("0");
            returnBody.setTitle("成功");
        } catch (Exception var5) {
            returnBody.setCode("1");
            returnBody.setTitle("系统错误");
        }
        return returnBody;
    }

    @Override
    public ReturnBody roleStateNavig(JSONObject jsonObject) {
        NavigRoleGroup entity = new NavigRoleGroup();
        entity.setFspRole((FspRole) BeanToJson.jsonTobean(jsonObject.get("fspRole").toString(), FspRole.class));
        entity.setFspNavigationList(com.alibaba.fastjson.JSONObject.parseArray(jsonObject.getJSONArray("fspNavigationList").toString(), FspNavigation.class));
        ReturnBody returnBody = new ReturnBody();
        try {
            FspRoleNavigation fspNavigationINS=new FspRoleNavigation();
            fspNavigationINS.setUuid("");
            StringBuilder del  = new StringBuilder();
            del.append(" ' '");
            for(FspNavigation fspNavigation:entity.getFspNavigationList()){
                if(fspRoleDataDao.custom("select * from fsp_role_navigation where f_role_code = '"+entity.getFspRole().getF_ROLE_CODE()+"' and f_navigation_id = '"+fspNavigation.getUuid()+"'")==null){
                    fspNavigationINS.setF_NAVIGATION_ID(fspNavigation.getUuid());
                    fspNavigationINS.setF_ROLE_CODE(entity.getFspRole().getF_ROLE_CODE());
                    actuatorController.execute(fspNavigationINS,"add",fspRoleNavigationDao);
                }
                del.append(",'"+fspNavigation.getUuid()+"'");
            }
            mpsDao.commonSqlUp("delete from fsp_role_navigation where f_navigation_id not in ("+del.toString()+") and f_role_code = '"+entity.getFspRole().getF_ROLE_CODE()+"'");
            this.upRoleNum(entity.getFspRole().getF_ROLE_CODE());
            returnBody.setCode("0");
            returnBody.setTitle("成功");
        } catch (Exception var5) {
            returnBody.setCode("1");
            returnBody.setTitle("系统错误");
        }
        return returnBody;
    }

    private void upRoleNum(String roleCode){
        int dataNum = fspRoleDataDao.getNum("f_role_code",roleCode);
        int lookNum = fspRoleLookDao.getNum("f_role_code",roleCode);
        int navigNum = fspRoleNavigationDao.getNum("f_role_code",roleCode);
        fspRoleDao.update("f_role_num",String.valueOf(dataNum+lookNum+navigNum),"f_role_code",roleCode);
    }
    private void addRole(String roleCode) throws Exception {
        FspRoleLook fspRoleLook = new FspRoleLook();
        FspRoleData fspRoleData = new FspRoleData();
        FspRoleNavigation fspRoleNavigation =new FspRoleNavigation();
        fspRoleData.setF_ROLE_CODE(roleCode);
        fspRoleLook.setF_ROLE_CODE(roleCode);
        fspRoleNavigation.setF_ROLE_CODE(roleCode);
        fspRoleData.setUuid("");
        fspRoleLook.setUuid("");
        fspRoleNavigation.setUuid("");
        fspRoleData.setF_DATA_ID("1574998957821");
        fspRoleLook.setF_LOOK_ID("1574998957820");
        fspRoleNavigation.setF_NAVIGATION_ID("1555508458589");
        actuatorController.execute(fspRoleData,"add",fspRoleDataDao);
        actuatorController.execute(fspRoleLook,"add",fspRoleLookDao);
        actuatorController.execute(fspRoleNavigation,"add",fspRoleNavigationDao);
    }
}
